<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>for await...of</title>
</head>
<body>
    <h1>for await...of</h1>

    <script>
        // 基本用法
        async function basic() {
            const asyncIterable = {
                [Symbol.asyncIterator]() {
                    return {
                        i: 0,
                        async next() {
                            if (this.i < 3) {
                                return { value: this.i++, done: false };
                            }
                            return { value: undefined, done: true };
                        }
                    };
                }
            };

            for await (const value of asyncIterable) {
                console.log(value); // 0, 1, 2
            }
        }

        // 遍历异步生成器
        async function* asyncGenerator() {
            yield await Promise.resolve(1);
            yield await Promise.resolve(2);
            yield await Promise.resolve(3);
        }

        async function useGenerator() {
            for await (const value of asyncGenerator()) {
                console.log(value); // 1, 2, 3
            }
        }

        // 实际应用：分页数据加载
        class AsyncPageLoader {
            constructor(url, pageSize = 10) {
                this.url = url;
                this.pageSize = pageSize;
                this.currentPage = 0;
            }

            async *[Symbol.asyncIterator]() {
                while (true) {
                    const response = await fetch(
                        `${this.url}?page=${this.currentPage}&size=${this.pageSize}`
                    );
                    const data = await response.json();
                    
                    if (data.items.length === 0) {
                        break;
                    }

                    yield* data.items;
                    this.currentPage++;
                }
            }
        }

        // 使用分页加载器
        async function loadAllData() {
            const loader = new AsyncPageLoader('https://api.example.com/data');
            try {
                for await (const item of loader) {
                    console.log('加载数据:', item);
                }
            } catch (error) {
                console.error('加载失败:', error);
            }
        }
    </script>
</body>
</html> 